import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as qs from 'qs';
import { map, Subscription } from 'rxjs';
import { IResult } from 'src/app/pojo/IResult';
import IUser from 'src/app/pojo/IUser';
import { UserService } from 'src/app/service/user.service';

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss']
})
export class UserDetailComponent {

  // id: string = "";
  flag: string = ""; // 0:添加；1：编辑；2：删除
  id: string = "";
  registerForm: FormGroup;
    // 用于释放订阅
  private subscriptions: Subscription[] = [];

  constructor(private userService: UserService,
    private router: Router,
   private activateRoute: ActivatedRoute, 
    private formBuilder: FormBuilder) {

    this.registerForm = this.formBuilder.group({
      name: ['test', [Validators.required]],
      password: ['test', [Validators.required]],
      email: ['test@qq.com', [Validators.required, Validators.email]],
      phonenumber: ['18136392375', [Validators.required]],
      userimg: ['/upload/54fe4c03-8040-4cd9-9d02-cc49b2c58a55.png'] // This field is optional and can be left empty.
    });

  };

 
  goBack() {
    // 导航回上一个路由
    // this.router.navigate(['../'], { relativeTo: this.activateRoute.parent });
    // // 使用 ActivatedRoute 来获取当前激活路由的父级路由
    // const parentRoute = this.activateRoute.parent;
    // if (parentRoute) {
    //   // 导航回上一个页面
    //   this.router.navigate(['../'], { relativeTo: parentRoute });
    // } else {
    //   // 如果没有父级路由，则导航到根路由
    //   this.router.navigate(['/']);
    // }
    this.router.navigate(['/usermanager/userList'], { queryParams: { } });
  }
  
  onSubmit() {
    if (!this.registerForm || this.registerForm.invalid) {
      return;
    }

    const user: IUser = {
      // id:this.id,
      name: this.registerForm.get('name')?.value,
      password: this.registerForm.get('password')?.value,
      email: this.registerForm.get('email')?.value,
      phonenumber: this.registerForm.get('phonenumber')?.value,
      userimg: this.registerForm.get('userimg')?.value
    };
    if (this.flag=="1" || this.flag=="2"){
      user.id=this.id;
    }
    // 接口参数
    let payload = qs.stringify(user);
    // 通过服务读取用户列表
    // 定义一个用户列表观察者
    const subscription = this.userService.addupdateSaveUser(payload,this.flag).pipe(
    ).subscribe(
      {
        next: (result: IResult) => {
          console.log(result);
          this.router.navigate(['/usermanager/userList'], { queryParams: { } });
        },
        error: (error) => {
          console.error('Error:', error);
        },
        complete: () => console.log('Complete')
      }
    );
    
    this.subscriptions.push(subscription);
    // this.userService.register(user).subscribe(
    //   response => {
    //     console.log('Registration successful:', response);
    //     this.router.navigate(['/login']);
    //   },
    //   error => {
    //     console.error('Registration failed:', error);
    //   }
    // );
  }

  // 组件初始化
  ngOnInit() {
    // 路由参数
    this.activateRoute.params.subscribe(params => {
      console.log("----------UserDetailComponent-------------");
      this.id = params['id'];
      this.flag = params['flag'];
      
      if(this.flag=="1" || this.flag=="2"){

        const user: IUser = {
          id: this.id,
        };
        // 接口参数
        let payload = qs.stringify(user);

        const subscription = this.userService.getUsersById(payload).pipe(
          ).subscribe(
            {
              next: (users: IUser[]) => {
                if(users && users.length>0){
                  this.id=users[0].id as string;
                  this.registerForm = this.formBuilder.group({
                    name: [users[0].name, [Validators.required]],
                    password: [users[0].password, [Validators.required]],
                    email: [users[0].email, [Validators.required, Validators.email]],
                    phonenumber: [users[0].phonenumber, [Validators.required]],
                    userimg: [users[0].userimg,] // This field is optional and can be left empty.
                  });
              
                }
                
              },
              error: (error) => {
                console.error('Error:', error);
              },
              complete: () => console.log('Complete')
            }
          );
          
          this.subscriptions.push(subscription);

      }
      
    });


    // this.route.queryParams.subscribe(params => {
    //   this.name = params['name'];
    //   this.flag = params['flag'];
    //   console.log("----------UserDetailComponent-------------");
    //   console.log(this.name);
    //   console.log(this.flag);
    // });


  }
   // 组件销毁
   ngOnDestroy(): void {
    // 释放内存订阅器
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

}
